﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WAD.DAL;
using WAD.Model;
using System.Text.RegularExpressions;

namespace WAD.BLL
{
    public class FCCashBLL
    {
        static object lockObj = new object();
        /// <summary>
        /// 支付宝提现审核
        /// </summary>
        /// <param name="names"></param>
        /// <param name="adminid"></param>
        /// <param name="DES_KEY"></param>
        public static int Check_Ali(string names, int adminid, string DES_KEY)
        {
            int count = 0;
            StringBuilder sb = new StringBuilder();
            StringBuilder sb2 = new StringBuilder();
            lock (lockObj)
            {
                List<Dictionary<string, object>> list = DAOFCCash.GetList("orderid in(" + GetOrderIds(names) + ")", "id,user_id,orderid,amount,platform,state,openid", 50000);

                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i] == null) continue;
                    try
                    {
                        int state = Convert.ToInt32(list[i]["state"]);
                        if (state > 0)
                        {
                            sb.Append(list[i]["id"] + ",");
                            continue; //"不允许重复审核";
                        }

                        int amount = Convert.ToInt32(list[i]["amount"]);
                        if (amount < 0)
                        {
                            sb2.Append(list[i]["id"] + ",");
                            continue; //"提现金额无效";
                        }

                        int id = Convert.ToInt32(list[i]["id"]);
                        int user_id = Convert.ToInt32(list[i]["user_id"]);

                        //标记成已审核状态
                        DAOFCCash.Check(1, id, adminid, names.Split('|')[i]);
                        count++;
                    }
                    catch { }
                }

                if (sb.Length > 0 || sb2.Length > 0)
                    DaoLogcat.Add("ali_tixian", string.Format("支付宝重复提现ID:{0},金额小于0的ID:{1}", sb.ToString(), sb2.ToString()));
            }
            
            #region 2016-04-21 注释(性能低下)
            //lock (lockObj)
            //{
            //    List<string> list = GetOrderId(names);
               
            //    for (int i = 0; i < list.Count; i++)
            //    {
            //        try
            //        {
            //            Dictionary<string, object> model = DAOFCCash.Get("fc_cash", "orderid='" + list[i] + "'", "id,user_id,orderid,amount,platform,state,openid");
            //            if (model == null) continue;    //找不到记录

            //            int id = Convert.ToInt32(model["id"]);
            //            int user_id = Convert.ToInt32(model["user_id"]);
            //            int state = Convert.ToInt32(model["state"]);
            //            int amount = Convert.ToInt32(model["amount"]);

            //            if (state > 0)
            //            {
            //                DaoLogcat.Add("ali_tixian", "过滤重复提现! ID:" + id);
            //                continue; //"不允许重复审核";
            //            }
            //            if (amount < 0)
            //            {
            //                DaoLogcat.Add("ali_tixian", "提现金额<0 ! ID:" + id);
            //                continue; //"提现金额无效";
            //            }

            //            //Dictionary<string, object> user = DaoUser.GetDetail(user_id, "shared_balance");
            //            //decimal balance = DaoUser.BalanceDncode(user["shared_balance"], DES_KEY);
            //            //if (balance >= amount)
            //            //    DaoUser.UpdateBalance(user_id, (balance - amount), 2);  //余额充足，扣款
            //            //else
            //            //    DaoUser.UpdateBalance(user_id, 0, 2);   //余额不足，清零

            //            //标记成已审核状态
            //            DAOFCCash.Check(1, id, adminid, names.Split('|')[i]);
            //            count++;
            //        }
            //        catch { }
            //    }
            //}
            #endregion
            return count;
        }


        /// <summary>
        /// 支付宝提现失败处理(只包含： 支付宝账号、姓名不匹配)
        /// </summary>
        /// <param name="names"></param>
        /// <param name="adminid"></param>
        /// <param name="DES_KEY"></param>
        public static int Check_Ali_Fail(string names, int adminid, string DES_KEY)
        {
            int count = 0;
            List<string> list = GetOrderId(names);
            for (int i = 0; i < list.Count; i++)
            {
                try
                {
                    string callback_msg = names.Split('|')[i];
                    //标记成失败状态
                    DAOFCCash.Check_Ali_Fail(2, list[i], adminid, callback_msg, GetMsg(callback_msg));
                    count++;
                }
                catch { }
            }
            return count;
        }


        static List<string> GetOrderId(string names)
        {
            //names = 批量付款中成功付款的信息。 格式为：流水号^收款方账号^收款账号姓名^付款金额^成功标识(S)^成功原因(null)^支付宝内部流水号^完成时间。 每条记录以“|”间隔。
            string[] arr = names.Split('|');
            if (arr == null || arr.Length < 1) return null;

            List<string> list = new List<string>();
            for (int i = 0; i < arr.Length; i++)
            {
                if (string.IsNullOrEmpty(arr[i])) continue;

                string[] item = arr[i].Split('^');
                if (item == null || item.Length < 1) continue;

                list.Add(item[0]);  //订单号
            }
            return list;
        }

        static string GetOrderIds(string names)
        {
            //names = 批量付款中成功付款的信息。 格式为：流水号^收款方账号^收款账号姓名^付款金额^成功标识(S)^成功原因(null)^支付宝内部流水号^完成时间。 每条记录以“|”间隔。
            string[] arr = names.Split('|');
            if (arr == null || arr.Length < 1) return null;

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < arr.Length; i++)
            {
                if (string.IsNullOrEmpty(arr[i])) continue;

                string[] item = arr[i].Split('^');
                if (item == null || item.Length < 1) continue;

                sb.AppendFormat(",'{0}'", item[0]);//订单号
            }
            arr = null;
            if (sb.Length > 0)
                sb.Remove(0, 1);
            return sb.ToString();
        }

        static string GetMsg(string html)
        {
            Regex r1 = new Regex("\\^F\\^([\\s\\S].*?)\\^");
            if (r1.IsMatch(html))
                return FormatMsg(r1.Match(html).Groups[1].Value);
            return "提现失败";
        }

        static string FormatMsg(string msg)
        {
            switch (msg)
            {
                case "USER_NOT_EXIST": msg = "用户不存在"; break;
                case "ACCOUN_NAME_NOT_MATCH": msg = "用户姓名和收款名称不匹配"; break;
                case "RECEIVE_EMAIL_NAME_NOT_MATCH": msg = "收款方email账号与姓名不匹配"; break;
                case "RECEIVE_USER_NOT_EXIST": msg = "收款用户不存在"; break;
                case "RECEIVE_ACCOUNT_ERROR": msg = "收款账户有误或不存在"; break;
                case "RECEIVE_SINGLE_MONEY_ERROR": msg = "收款金额超限"; break;
                case "TRANSFER_AMOUNT_NOT_ENOUGH": msg = "转账余额不足"; break;
                case "DETAIL_OUT_BIZ_NO_REPEATE": msg = "同一批次中商户流水号重复"; break;
                case "PAYER_ACCOUNT_IS_RELEASED": msg = "付款账户名与他人重复"; break;
                case "BATCH_NO_NULL": msg = "批次号为空"; break;
                case "ERROR_ACCESS_DATA": msg = "无权访问该数据"; break;
                case "ERROR_FILE_NAME_LENGTH": msg = "过长的文件名"; break;
                case "ERROR_BALANCE_NULL": msg = "用户余额不存在"; break;
                case "ERROR_USER_INFO_NULL": msg = "用户信息为空"; break;
                case "ERROR_USER_ID_NULL": msg = "用户名为空"; break;
                case "ERROR_BATCH_ID_NULL": msg = "批次ID为空"; break;
                case "ERROR_BATCH_NO_NULL": msg = "批次号为空"; break;
                case "RECEIVE_EMAIL_ERROR": msg = "收款人EMAIL不能为空或必须小于100个字符"; break;
                case "RECEIVE_NAME_ERROR": msg = "收款人姓名不能为空或必须小于128个字符"; break;
                case "ILLEGAL_USER_STATUS": msg = "用户状态不正确"; break;
                case "ERROR_OTHER_NOT_REALNAMED": msg = "收款账户尚未实名认证，无法收款"; break;
                case "ILLEGAL_CONTENT_FORMAT": msg = "文件内容格式非法"; break;
            }
            return msg;
        }
    }
}